package cn.net.isir.controller.manager;

import cn.net.isir.common.ResultObject;
import cn.net.isir.common.TokenManager;
import cn.net.isir.core.BasicController;
import cn.net.isir.core.SetBasicService;
import cn.net.isir.entity.Message;
import cn.net.isir.entity.MessageReadStatus;
import cn.net.isir.entity.Organizations;
import cn.net.isir.entity.UserInfo;
import cn.net.isir.service.*;
import cn.net.isir.utils.StringUtils;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author liuxubo
 * @filename MessageController.java
 * @package cn.net.isir.controller.manager
 * @email lxb@isir.net.cn
 * @date 2019/02/22
 * @comment 通知管理
 * @since 1.8
 */
@RestController
@RequestMapping("/message")
public class MessageController extends BasicController<Message> {
    @SetBasicService
    @Resource
    private MessageService messageService;
    @Resource
    private CRMUserManagerService crmUserManagerService;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private OrganizationsService organizationsService;
    @Resource
    private MessageReadStatusService messageReadStatusService;

    /**
     * 根据用户id查询信息
     *
     * @param message 参数
     * @return 列表
     */
    @Override
    public ResultObject selectListByUser(Message message) {
        Set<String> userIds = crmUserManagerService.getSalesmanIdByUserId(TokenManager.getTokenId());
        // 搜索内容转码
        if (StringUtils.isNotBlank(message.getContent())) {
            try {
                message.setContent(URLDecoder.decode(message.getContent(), StandardCharsets.UTF_8.name()));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        // 增加自己发布的列表
        userIds.add(TokenManager.getTokenId());
        String ids = StringUtils.collectionsToCommas(userIds);
//        Map<String, Object> extraParams = new HashMap<>();
//        extraParams.put("userIds", ids);
//        message.setExtraParams(extraParams);
        message.setIds(ids);
        PageInfo pageInfo = messageService.selectPageList(message, message.getPageNo(), message.getPageSize());
//        List<Message> list = pageInfo.getList();
//        list.forEach(i -> {
//            UserInfo userInfo = userInfoService.selectByUserId(i.getCreater());
//            if (userInfo != null) {
//                i.setCreater(userInfo.getName());
//            } else {
//                i.setCreater(null);
//            }
//        });
//        pageInfo.setList(list);
        return new ResultObject(200, "success", pageInfo);
    }

    /**
     * 获取用户消息详情
     *
     * @param message 消息
     * @return 返回列表
     */
    @RequestMapping(value = "/getMyOrgMessage", method = RequestMethod.GET)
    public ResultObject getMyOrgMessage(Message message) {
        Organizations org = crmUserManagerService.getOrgByUserId(TokenManager.getTokenId());
        List<Organizations> pOrgList = crmUserManagerService.getParentsOrgByOrgId(org.getId());
//        String pOrgOR = StringUtils.collectionsToCommas();
        String pOrgOR = StringUtils.collectionsToCommas(pOrgList, Organizations::getId);
        if (StringUtils.isNotBlank(pOrgOR)) {
            pOrgOR = pOrgOR.replace(",", "|");
        }
        PageInfo<Message> info = messageService.getMyOrgMessage(pOrgOR, message.getContent(),
                message.getPageNo(), message.getPageSize(), TokenManager.getTokenId());

        return new ResultObject(200, "success", info);
    }

    /**
     * 获取组织机构
     *
     * @param id 消息通知列表
     * @return 列表
     */
    @RequestMapping(value = "/getMsgOrgs/{id}", method = RequestMethod.GET)
    public ResultObject getMsgOrgs(@PathVariable String id) {
        Message message = messageService.selectByPrimaryKey(id);
        String ids = message.getOrgIds();
        List<Organizations> orgList = new ArrayList<>();
        if (ids != null && !"".equals(ids)) {
            for (String s : ids.split(",")) {
                List<Organizations> subOrgList = crmUserManagerService.getOrgListByOrgId(s);
                // 如果没有查询到子组织机构，初始化一个空的列表
                if (subOrgList == null || subOrgList.size() == 0) {
                    subOrgList = new ArrayList<>();
                }
                // 增加父级机构
                Organizations o = organizationsService.selectByPrimaryKey(s);
                if (o != null) {
                    subOrgList.add(o);
                }
                // 循环子级机构
                for (Organizations org : subOrgList) {
                    boolean isExist = false;
                    for (Organizations organizations1 : orgList) {
                        if (organizations1.getId().equals(org.getId())) {
                            isExist = true;
                        }
                    }
                    if (!isExist) {
                        orgList.add(org);
                    }
                }
            }
            return new ResultObject(200, "success", orgList);
        }
        return new ResultObject(200, "success", new ArrayList<>());

    }

    /**
     * 切换发布状态
     *
     * @param message 消息
     *
     * @return 结果
     */
    @RequestMapping(value = "/togglePublishStatus", method = RequestMethod.PUT)
    public ResultObject togglePublishStatus(@RequestBody Message message) {
        if (StringUtils.isBlank(message.getId())) {
            return new ResultObject(500, "id is blank", null);
        }
        if (message.getIsPublished() == null) {
            return new ResultObject(500, "publish status is blank", null);
        }
        Message updateDto = new Message();
        updateDto.setId(message.getId());
        updateDto.setIsPublished(message.getIsPublished());
        // 如果是发布更新,则设置发布时间
        if (message.getIsPublished() == 1) {
            message.setPublishTime(new Date());
        }
        int result = messageService.update(updateDto);
        return new ResultObject(200, "success", result);
    }

    @Override
    public ResultObject query(@PathVariable String id) {
        Message message = messageService.selectByPrimaryKey(id);
        // 如果没有组织机构，不做处理
        if (StringUtils.isBlank(message.getOrgIds())) {
            return new ResultObject(200, "success", message);
        }
        // 如果有组织机构，先判断是否删掉了，如果未删掉，再展示出来
        StringBuilder sb = new StringBuilder();
        for (String s : message.getOrgIds().split(",")) {
            Organizations o = organizationsService.selectByPrimaryKey(s);
            if (o != null) {
                sb.append(o.getId()).append(",");
            }
        }
        // 重新回填组织机构列表，返回前台
        String finalOrgIds = sb.length() == 0 ? sb.toString() : sb.substring(0, sb.length() - 1);
        message.setOrgIds(finalOrgIds);
        return new ResultObject(200, "success", message);
    }

    /**
     * 查询信息
     *
     * @param id 主键
     * @return 结果
     */
    @RequestMapping(value = "/read/{id}", method = RequestMethod.GET)
    public ResultObject read(@PathVariable String id) {
        Message message = messageService.selectByPrimaryKey(id);
        MessageReadStatus readStatus = new MessageReadStatus();
        readStatus.setMsgId(message.getId());
        readStatus.setUserId(TokenManager.getTokenId());
        MessageReadStatus readStatus2 = messageReadStatusService.selectOne(readStatus);
        if (readStatus2 == null) {
            readStatus.setReadTime(new Date());
            messageReadStatusService.insert(readStatus);
        }
        return new ResultObject(200, "success", message);
    }

}
